import { init as pickerInit, $ } from './picker/index';
import { panelColor, standardColor, commColor } from './config.js';
let outside = false; //点击范围判断
let hoverSide = false; // 移入范围判断
let targetParam; // 目标id
const colorId = 'ui-color'; //组件id
const pickercOpenId = 'ui-color-more-open'; // 开启取色器的目标
let initDB = false; // 是否初始化
let cancelClassName = 'luckysheet-mousedown-cancel';
let colorOption; // 外部监听对象
let pickercOption = {}; // 取色器监听对象
const htmlText = `<div class="ui-color-contents ${cancelClassName}">
        <div class="ui-color-none ${cancelClassName}">
          无填充
        </div>
        <div class="ui-color-panel ${cancelClassName}"></div>
        <p class="ui-color-tip ${cancelClassName}">标准色</p>
        <div class="ui-color-standard ${cancelClassName}"></div>
        <p class="ui-color-tip ${cancelClassName}">常用</p>
        <div class="ui-color-common ${cancelClassName}"></div>
      </div>
      <div id="ui-color-more-open" class="ui-color-more ${cancelClassName}">
        <div class="ui-color-more-left ${cancelClassName}">
          <i class="${cancelClassName}"></i>
          <span class="${cancelClassName}">更多颜色</span>
        </div>
        <i class="iconfont icon-caret-right ${cancelClassName}">
        </i>
      </div>`;
// 常用颜色获取
function commColorCheck() {
  let list = localStorage.getItem('commColor');
  if (list) list = JSON.parse(list);
  if (list && list.length > 0) {
    setCommColorFn(list);
  } else {
    localStorage.setItem('commColor', JSON.stringify(commColor));
  }
}
export function init(value, param) {
  targetParam = value;
  let dom;
  let target = $(`#${targetParam.id}`);
  if (initDB) {
    commColorCheck();
    dom = $(`#${colorId}`);
  } else {
    colorOption = param;
    initDB = true;
    dom = document.createElement('div');
    dom.id = colorId;
    dom.className = `ui-color ${cancelClassName}`;
    dom.setAttribute('seleced', '');
    dom.innerHTML = htmlText;
    window.addEventListener('mouseup', onSpaceFn);
    document.body.appendChild(dom);
    dom.onmousedown = () => {
      outside = true;
    };
    // 无色选项绑定事件
    dom.children[0].children[0].onclick = () => {
      change('transparent', 1, param);
    };
    updatePanel();
    updateStandard();
    updateCommon();
    pickercOption = {
      confirm: function (item, type) {
        colorOption.colorChange(item, type, targetParam);
        const uiColor = $(`#${colorId}`);
        uiColor.seleced = item;
        uiColor.style.display = 'none';
      },
      hoverHide: function () {
        hoverHide();
      }
    };
    pickerInit({ id: pickercOpenId, mode: 'hover' }, pickercOption);
  }
  if (!target) return;
  dom.style.cssText = `display: none;left: ${target.offsetLeft}px;top: ${target.offsetTop + target.clientHeight}px`;
  if (targetParam.mode === 'hover') {
    target.onmouseenter = () => {
      hoverVisible(value);
    };
    target.onmouseleave = e => {
      setTimeout(() => {
        hoverHide(value, e);
      });
    };
    dom.onmouseenter = () => {
      hoverSide = true;
    };
    dom.onmouseleave = () => {
      hoverSide = false;
      hoverHide();
    };
  } else {
    target.addEventListener('click', () => {
      changeHide(value);
    });
  }
}

/*******
 * @Author: 刘强
 * @description: 颜色选择
 * @param {*} item:选中的色值
 * @param {*} type:选择的类型 0常用，1无填充，2取色器，3标准，4面板
 *
 */
function change(item, type) {
  const uiColor = $('#ui-color');
  uiColor.seleced = item;
  uiColor.style.display = 'none';
  if (type > 2) commCheck(item);
  colorOption.colorChange(item, type, targetParam);
}
// 目标点击显示/隐藏
function changeHide(value = targetParam) {
  if (value.mode === 'hover') return;
  targetParam = value;
  let dom = $(`#${colorId}`);
  let visible = dom.style.display;
  dom.style.display = visible === 'none' ? 'block' : 'none';
  if (visible === 'none') opsitionFn();
}
// hover模式显示
function hoverVisible(value = targetParam) {
  if (value.mode === 'click') return;
  targetParam = value;
  let dom = $(`#${colorId}`);
  dom.style.display = 'block';
  opsitionFn();
}
//hover模式隐藏
function hoverHide(value = targetParam) {
  if (value.mode === 'click') return;
  if (!hoverSide) {
    let dom = $(`#${colorId}`);
    dom.style.display = 'none';
  }
}
// 点击空白判断
function onSpaceFn(e) {
  if (e.target.classList.contains(cancelClassName)) return;
  if (outside) {
    outside = false;
  } else {
    let dom = $('#ui-color');
    if (dom.style.display === 'block') changeHide();
  }
}
// 常用颜色变化
function commCheck(item) {
  let target = -1;
  for (let i = 0; i < commColor.length; i++) {
    if (commColor[i] === item) {
      target = i;
      break;
    }
  }
  if (target === -1) {
    commColor.unshift(item);
    commColor.pop();
  } else {
    commColor.splice(target, 1, commColor[0]);
    commColor.splice(0, 1, item);
  }
  updateCommon();
}
// render列
function renderTd(arr, type) {
  return arr.map(item => {
    let dom = document.createElement('span');
    dom.onclick = () => {
      change(item, type);
    };
    dom.className = 'ui-color-td';
    dom.style.cssText = `background:${item}`;
    return dom;
  });
}
// 更新panel
export function updatePanel() {
  let dom = $('#ui-color').children[0].children[1];
  dom.innerHTML = '';
  for (let i = 0; i < panelColor.length; i++) {
    let domtr = document.createElement('div');
    domtr.className = 'ui-color-tr';
    const domtd = renderTd(panelColor[i], 3);
    for (let j = 0; j < domtd.length; j++) {
      domtr.appendChild(domtd[j]);
    }
    dom.appendChild(domtr);
  }
}
// 更新标准色
export function updateStandard(index = -1, value = '') {
  if (index !== -1) {
    standardColor[index] = value;
  }
  let dom = $('#ui-color').children[0].children[3];
  dom.innerHTML = '';
  const listDom = renderTd(standardColor, 2);
  for (let i = 0; i < listDom.length; i++) {
    dom.appendChild(listDom[i]);
  }
}
// 更新常用
export function updateCommon(index = -1, value = '') {
  if (index !== -1) {
    commColor[index] = value;
  }
  let dom = $('#ui-color').children[0].children[5];
  dom.innerHTML = '';
  const listDom = renderTd(commColor, 0);
  for (let i = 0; i < listDom.length; i++) {
    dom.appendChild(listDom[i]);
  }
  //if (localStorage) localStorage.setItem('commColor', JSON.stringify(commColor));
}
// 打开时自动调整位置
function opsitionFn() {
  const dom = $(`#${colorId}`);
  const target = $(`#${targetParam.id}`);
  const targetClient = target.getBoundingClientRect();
  const leftNum = 2,
    topNum = 2; // 间隙
  let left = 0,
    top = 0;
  // right模式
  switch (targetParam.position) {
    case undefined:
    case 'rightBottom':
      left = targetClient.left + leftNum;
      top = targetClient.top + target.clientHeight;
      // 判断右边是否被遮挡-是否需要改为左边模式
      if (left + dom.clientWidth > window.innerWidth) {
        left = targetClient.right - dom.clientWidth;
      }
      // 判断底部是否被遮挡
      if (top + dom.clientHeight > window.innerHeight) {
        let newTop = targetClient.top - dom.clientHeight - topNum;
        top = newTop > 0 ? newTop : top;
      }
      break;
    case 'right':
      left = targetClient.left + target.clientWidth + leftNum;
      top = targetClient.top;
      // 判断右边是否被遮挡-是否需要改为左边模式
      if (left + dom.clientWidth > window.innerWidth) {
        left = targetClient.right - dom.clientWidth - target.clientWidth;
      }
      // 判断底部是否被遮挡
      if (top + dom.clientHeight > window.innerHeight) {
        let newTop = targetClient.top - dom.clientHeight + target.clientHeight;
        top = newTop > 0 ? newTop : top;
      }
      break;
  }
  dom.style.cssText = `${dom.style.cssText};left: ${left}px;top: ${top}px;`;
}
// 常用色值队列设置默认值
export function setCommColorFn(value) {
  commColor.splice(0, commColor.length);
  for (let i = 0; i < value.length; i++) {
    commColor.push(value[i]);
  }
}
